<?php
/**
 * Created by PhpStorm
 * User: honglin
 * Date: 2022/8/8
 * Time: 下午3:13
 */

namespace App\Service\Ocean;

use App\Constants\OceanEvent;
use App\Dao\Ocean\OceanPowerLogDao;
use App\Dao\Ocean\OceanTaskDao;
use App\Dao\Ocean\OceanTaskLogDao;
use App\Dao\User\UserDao;
use App\Event\Ocean\OceanAd;
use App\Event\Ocean\OceanSignIn;
use App\Event\Ocean\OceanUserRubbishClear;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class OceanTaskService
{
    /**
     * @Inject()
     * @var OceanTaskDao
     */
    protected $oceanTaskDao;

    /**
     * @Inject()
     * @var OceanTaskLogDao
     */
    protected $oceanTaskLogDao;

    /**
     * @Inject()
     * @var OceanPowerLogDao
     */
    protected $oceanPowerLogDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    public function finish($userId, $task_id)
    {
        //判断是否完成
        //已经完成
        $power = $this->oceanTaskDao->where('id', $task_id)->value('num');
        Db::beginTransaction();
        try {
            $nowData = date('Y-m-d');

            if($oceanPowerLog = $this->oceanPowerLogDao
                ->where('task_id',$task_id)
                ->where('user_id', $userId)
                ->where('date', $nowData)
                ->exists()){
                _Error('已经完成了');
            }else{
                $this->oceanPowerLogDao->create([
                    'user_id' => $userId,
                    'task_id' => $task_id,
                    'power' => $power,
                    'date' => $nowData
                ]);
                $this->userDao->where('uid', $userId)->increment('ocean_power', $power);
            }

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            _Error($exception->getMessage());
        }
        return true;
    }

    public function signIn($userId)
    {
        event()->dispatch(new OceanSignIn($userId));
        return true;
    }


    public function getUserTaskLists($userId)
    {
        $date = date('Y-m-d');

        $lists = $this->oceanTaskDao->page(false)->getList();
        $taskLog = $this->oceanTaskLogDao->where('date', $date)
            ->where('user_id', $userId)->select([Db::raw('count(task_id) as count_task_id'), 'task_id'])
            ->groupBy('task_id')
            ->get();

        $lists->transform(function ($item) use ($taskLog, $date) {
            $item->finish_times = $taskLog->where('task_id', $item->id)
                    ->first()['count_task_id'] ?? 0;
            $item->finish_times = min($item->finish_times, $item->max_times);
            $item->is_receive = $this->oceanPowerLogDao
                ->where('task_id', $item->id)->where('date', $date)->exists() ? 1 : 0;
            return $item;
        });
        return $lists;
    }

    public function Ad($userId)
    {
        event()->dispatch(new OceanAd($userId));
        return true;
    }

 
}